package com.core.family.gen.service.gen.Impl.postgre;

import com.core.family.gen.domain.po.TableBeanPo;
import com.core.family.gen.domain.po.TableColumnPo;
import com.core.family.gen.service.gen.Impl.AbsGenHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: mybatis 相关代码生成 通过链接器获取数据库元信息实现
 * @author: honglei
 * @time: 2021/3/23 0023 14:48
 */

public class GenPostGreHandler extends AbsGenHandler {

    //oracle 查询表名
    //  SELECT * from pg_tables WHERE schemaname ='midsap'
    // SELECT   * FROM pg_description
    private final static String QUEARY_TABLEAS =
            "SELECT c.relname AS TABLE_NAME,col_description(c.oid, 0) AS REMARKS " +
                    " FROM  pg_class c  " +
                    " LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
                    " WHERE " +
                    "  c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog', 'information_schema') ";


    //查询表字段及注释
    private final static String QUEARY_COLUMNS =
            " SELECT col.table_catalog, " +
                    " col.table_schema   AS tableSchema, " +
                    " col.table_name     AS tableName, " +
                    " col.column_name    AS COLUMN_NAME, " +
                    " col.data_type      AS dataType, " +
                    " col.udt_name       AS TYPE_NAME, " +
                    " d.description      AS REMARKS " +
                    " FROM information_schema.columns col " +
                    " JOIN pg_class c ON c.relname = col.table_name " +
                    " LEFT JOIN pg_description d ON d.objoid = c.oid " +
                    " AND d.objsubid = col.ordinal_position " +
                    " WHERE col.table_name = ? ";


    @Override
    public List<TableBeanPo> tablesList() throws Exception {
        List<TableBeanPo> list = new ArrayList<>();

        if (list.size() == 0) {
            Connection connection = getConnection();
            ResultSet rs = connection.createStatement().executeQuery(QUEARY_TABLEAS);
            list = filledTableBean(rs);
            connection.clearWarnings();
        }
        return list;
    }


    @Override
    public List<TableColumnPo> getColumns(String table) throws Exception {

        List<TableColumnPo> list = new ArrayList<>();

        if (list.size() == 0) {
            Connection connection = getConnection();
            PreparedStatement ps = connection.prepareStatement(QUEARY_COLUMNS);
            ps.setString(1, table);
            ResultSet resultSet = ps.executeQuery();
            list = filledTableColumn(resultSet);
            connection.close();
        }
        return list;
    }
}
